package com.brkj.main;


import android.app.Activity;
import android.app.LocalActivityManager;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Shader.TileMode;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TextView;

import com.brkj.alarm.DeskClockMainActivity;
import com.brkj.communityStudy.CommunityStudyActivity;
import com.brkj.course.CourseActivity;
import com.brkj.course.StudyHistoryActivity;
import com.brkj.footprint.SettingActivity;
import com.brkj.personalCenter.MoreActivity;
import com.brkj.personalCenter.NoticeActivity;
import com.brkj.search.SearchActivity;
import com.brkj.test.ExamActivity;
import com.brkj.test.TestMainActivity;
import com.brkj.util.BitmapUtil;
import com.brkj.util.CheckUpdate;
import com.brkj.util.ImgShow;
import com.brkj.util.MyApplication;
import com.dgl.sdk.util.FileDownloader;
import com.dgl.sdk.view.CircleImageView;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.jeremyfeinstein.slidingmenu.lib.app.SlidingFragmentActivity;

public class MainTabActivity extends SlidingFragmentActivity {
    /** Called when the activity is first created. */
	String[] title = new String[]{"课程","知识库","题库学习","调查考试","社区学习"};
	View courseTab,searrchTab,downloadTab,testTab, moreTab;
	View[] tabs = new View[]{courseTab, searrchTab,downloadTab,testTab, moreTab};

	TextView newActions_1, newActions_2, newActions_3, newActions_4, newActions_5;
	TextView[] newActions = new TextView[5];
//	ImageView[] newActions = new ImageView[]{newActions_1, newActions_2, newActions_3, newActions_4, newActions_5};
	
	BitmapDrawable bd;
	TabHost tabHost;
	
	private LocalActivityManager lam;
	private long exitTime;
    public static SlidingMenu sm;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tab_content);

        setBehindContentView(R.layout.personal_center);

        // customize the SlidingMenu
        sm = getSlidingMenu();
        sm.setMode(sm.LEFT);
        sm.setShadowWidthRes(R.dimen.shadow_width);
        sm.setShadowDrawable(R.drawable.shadowleft);
        sm.setBehindOffsetRes(R.dimen.slidingmenu_offset);
        sm.setFadeDegree(0.35f);
        sm.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);

        sm.setOnOpenedListener(new SlidingMenu.OnOpenedListener() {

            @Override
            public void onOpened() {


            }
        });

        tabHost = (TabHost)findViewById(R.id.tabhost);
        tabHost.setup();   //Call setup() before adding tabs if loading TabHost using findViewById().
        
        lam = new LocalActivityManager(MainTabActivity.this, false);
        lam.dispatchCreate(savedInstanceState);
 
        tabHost.setup(lam);
//        tabHost.setup(this.getLocalActivityManager());   
        
		Bitmap bitmap1 = BitmapFactory.decodeResource(this.getResources(), R.drawable.none);
		bd = new BitmapDrawable(bitmap1);  
		bd.setTileModeXY(TileMode.REPEAT , TileMode.CLAMP );  
		bd.setDither(true);  
		
		Intent intent0 = new Intent(this, CourseActivity.class);
		
		Intent intent1 = new Intent(this, SearchActivity.class);
		
		Intent intent2 = new Intent(this, ExamActivity.class);

		Intent intent3 = new Intent(this, TestMainActivity.class);
		Intent intent4 = new Intent(this, CommunityStudyActivity.class);
		
		Intent[] intentArray = new Intent[]{intent0, intent1, intent2, intent3, intent4};
		
		Drawable drawable1 = getResources().getDrawable(R.drawable.maintab_selector_0);
		Drawable drawable2 = getResources().getDrawable(R.drawable.maintab_selector_1);
		Drawable drawable3 = getResources().getDrawable(R.drawable.maintab_selector_2);
		Drawable drawable4 = getResources().getDrawable(R.drawable.maintab_selector_3);
		Drawable drawable5 = getResources().getDrawable(R.drawable.maintab_selector_4);
		
		Drawable[] iconList = new Drawable[]{drawable1, drawable2, drawable3, drawable4,drawable5};
		
        for(int i=0;i<tabs.length;i++){
        	tabs[i] = LayoutInflater.from(this).inflate(R.layout.tabmini, null);        	 		
  
        	//tabs[i].setBackgroundDrawable(bd);
        	
            tabHost.addTab(tabHost.newTabSpec(title[i]).setIndicator(tabs[i]).setContent(intentArray[i]));
            
            TextView text = (TextView) tabs[i].findViewById(R.id.tab_label);
            View tab_bg = tabs[i].findViewById(R.id.tab_bg);
            View tab_forcusbg = tabs[i].findViewById(R.id.tab_forcusbg);
            ImageView tab_icon = (ImageView) tabs[i].findViewById(R.id.tab_icon);
//            newActions[i] = (TextView) tabs[i].findViewById(R.id.newActions);
            
//            tab_bg.setBackgroundDrawable(bd);
//            tab_forcusbg.setBackgroundDrawable(getResources().getDrawable(R.drawable.maintab_fg_selector));

            tab_icon.setBackgroundDrawable(iconList[i]);
            text.setText(title[i]); 
       
        }
        

        		
        tabHost.setCurrentTab(0);
        
        tabHost.setOnTabChangedListener(new OnTabChangeListener() {
			@Override
			public void onTabChanged(String tabId) {
//		        for(int i=0;i<tabs.length;i++){
//		            View tab_forcusbg = (View) tabs[i].findViewById(R.id.tab_forcusbg);		            
//		            if(tabHost.getCurrentTab()==i){
//		            	
//		            	tab_forcusbg.setVisibility(View.VISIBLE);
//		            }else{
//		            	tab_forcusbg.setVisibility(View.GONE);
//		            }
//	            }
				//摇一摇 换搜索关键词   切换界面 关闭 和开启
				if(SearchActivity.shakeListener!= null){
				       if(tabId.equals(title[1])){
				    	   SearchActivity.shakeListener.start();
				       }else{
				    	   SearchActivity.shakeListener.stop();
				       }
				}

	        }		
		});
        
//        newActions[1].setBackgroundResource(R.drawable.chat_group_num);
        new CheckUpdate(this, "main").StartUpdate();

        FillPersonalCenter();
    }


    @Override
	protected void onDestroy() {
//		unregisterReceiver(mBroadcastReceiver);
		super.onDestroy();
	}

//	@Override
//	public boolean onKeyDown(int keyCode, KeyEvent event) {
//		if (keyCode == KeyEvent.KEYCODE_BACK ) {
//	        if((System.currentTimeMillis() - exitTime) > 2000){
//	            showToast("再按一次退出掌上学苑 ");
//	            exitTime = System.currentTimeMillis();
//	        } else {
//	        	finish();
//	        }
//		}
//
//		return true;
//	}

	
	@Override
	     protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	         // 获取当前活动的Activity实例
	         Activity subActivity = lam.getCurrentActivity();
	         //判断是否实现返回值接口
	         if (subActivity instanceof OnTabActivityResultListener) {
	             //获取返回值接口实例
	             OnTabActivityResultListener listener = (OnTabActivityResultListener) subActivity;
	             //转发请求到子Activity
	             listener.onTabActivityResult(requestCode, resultCode, data);
	         }
	         super.onActivityResult(requestCode, resultCode, data);
	     }


    //侧边栏
    private void FillPersonalCenter() {
        initUserInfo();

        findViewById(R.id.notice).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainTabActivity.this, NoticeActivity.class);
                startActivity(intent);
            }
        });

        findViewById(R.id.studyAlarm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainTabActivity.this, DeskClockMainActivity.class);
                startActivity(intent);
            }
        });


        findViewById(R.id.edit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainTabActivity.this, SettingActivity.class);
                startActivity(intent);
            }
        });

        findViewById(R.id.studyHistory).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainTabActivity.this, StudyHistoryActivity.class);
                startActivity(intent);
            }
        });

        findViewById(R.id.more).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainTabActivity.this, MoreActivity.class);
                startActivity(intent);
            }
        });


    }


    private void initUserInfo() {
        final CircleImageView userHead = (CircleImageView) findViewById(R.id.userImg);

        if(MyApplication.myInfo.getMyHeadImg().exists()){

//            ImgShow.display(userHead, MyApplication.myInfo.getMyHeadImgPath());

//            //dgltodo  out of memory error
            userHead.setImageDrawable(BitmapUtil.FiletoDrawable(MyApplication.myInfo.getMyHeadImgPath()));
////            userHead.setBackgroundDrawable(BitmapUtil.FiletoDrawable(MyApplication.myInfo.getMyHeadImgPath()));
//
//            Bitmap bitmap=BitmapFactory.decodeFile(MyApplication.myInfo.getMyHeadImgPath());
//            if(bitmap == null){
//                ImgShow.display(userHead, MyApplication.myInfo.getHeadUrl());
//            }else{
//                userHead.setImageBitmap(bitmap);
//            }
//
////            Bitmap output= BitmapUtil.toRoundBitmap(bitmap);
////            userHead.setImageBitmap(output);

        }else{
//            ImgShow.display(userHead, MyApplication.myInfo.getHeadUrl());
            FileDownloader fileDownloader = new FileDownloader(this, MyApplication.myInfo.getHeadUrl(),
                    MyInfo.MY_HEAD_IMG_PATH, MyInfo.MY_HEAD_IMG_NAME, 1, new FileDownloader.DownloadCallback() {
                @Override
                public void onStart() {

                }

                @Override
                public void onProgress(int progress) {

                }

                @Override
                public void onComplete(String filePath) {
                    userHead.setImageDrawable(BitmapUtil.FiletoDrawable(filePath));
                }

                @Override
                public void onError(String error) {

                }
            });

            fileDownloader.download();
        }

        ((TextView)findViewById(R.id.name)).setText(MyApplication.myInfo.getName());
        ((TextView)findViewById(R.id.jifen)).setText(Integer.toString(MyApplication.myInfo.getJifen()));

    }
}

